package se.webbzon.boltzmann.editor.component.dependencylist;

import java.util.Collection;
import java.util.Comparator;

import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;

import se.webbzon.boltzmann.editor.comparator.WorldObjectComparator;
import se.webbzon.boltzmann.editor.component.AbstractComponent;
import se.webbzon.boltzmann.editor.list.InstanceListCell;
import se.webbzon.boltzmann.editor.list.NullableSortedComboBoxModel;
import se.webbzon.boltzmann.editor.mvc.EditorModel;
import se.webbzon.oschi01.worldobject.WorldObject;

public class DependencyComboBox<T extends WorldObject> extends AbstractComponent {
	
	// Auto generated serial version UID
	private static final long serialVersionUID = -7752658166779818086L;
	
	// The combo boxes of this panel
	private JComboBox<T> dependencyBox;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public DependencyComboBox(EditorModel model, Class<T> clazz) {
		this(model,clazz,null,null);
	}
	
	public DependencyComboBox(EditorModel model, Class<T> clazz, String label) {
		this(model,clazz,null,label);
	}
	
	public DependencyComboBox(EditorModel model, Class<T> clazz, T selection) {
		this(model,clazz,selection,null);
	}
	
	public DependencyComboBox(	EditorModel model, Class<T> clazz, 
								T selection, String label) {
		super("Dependency");
		setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
		if (label != null)
			add(new JLabel(label));
		
		Collection<T> collection = model.getWorld().findInstances(clazz);
		@SuppressWarnings("unchecked")
		Comparator<T> comparator = (Comparator<T>) new WorldObjectComparator();
		NullableSortedComboBoxModel<T> dependencyBoxModel = 
				new NullableSortedComboBoxModel<T>(clazz,comparator,collection);
		dependencyBox = new JComboBox<T>(dependencyBoxModel);
		dependencyBox.setSelectedItem(selection);
		dependencyBox.setRenderer(new InstanceListCell());
		add(dependencyBox);
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Sets the selected world object in this dependency combo box. **/
	public void setInstance(T instance) {
		dependencyBox.setSelectedItem(instance);
	}
	
	/** Returns the selected world object in this dependency combo box. **/
	@SuppressWarnings("unchecked")
	public T getInstance() {
		return (T) dependencyBox.getSelectedItem();
	}

	@Override public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		dependencyBox.setEnabled(enabled);
	}
	
	

}
